﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using AMM.Model;
using AMM.Model.Store;

namespace AMM.DataAccess.Store {
    public class QualityOrderRepository : BaseRepository<QualityOrder> {

        private int _pageSize;

        public QualityOrderRepository(int pageSize = int.MaxValue) {
            this._pageSize = pageSize;
        }

        public QualityOrder FetchQualityOrderById(int qualityOrderId) {
            using (var ctx = this.Context) {
                return ctx.QualityOrders
                    .Include("QualityOrderDetails")
                    .FirstOrDefault(x => x.QualityOrderId == qualityOrderId);
            }
        }

        public QualityOrder FetchQualityOrderBySuspenseId(int suspenseOrderId) {
            using (var ctx = this.Context) {
                return ctx.QualityOrders
                    .Include("QualityOrderDetails")
                    .FirstOrDefault(x => x.SuspenseOrderId == suspenseOrderId && x.Status == 2);
            }
        }

        public QualityOrder FetchQualityOrderByIdForView(int qualityOrderId) {
            using (var ctx = this.Context) {
                return ctx.QualityOrders
                    .Include("SuspenseOrder")
                    .Include("QualityOrderDetails")
                    .Include("QualityOrderDetails.Material")
                    .FirstOrDefault(x => x.QualityOrderId == qualityOrderId);
            }
        }

        public void UpdateQualityOrder(QualityOrder qualityOrder) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        qualityOrder.QualityOrderDetails.Where(x => x.ClassStatus == ClassStatus.Added).ToList().ForEach(x => {
                            x.QualityOrder = qualityOrder;
                            x.QualityOrderId = qualityOrder.QualityOrderId;
                            x.QualityOrderDetailsId = Guid.NewGuid().GetHashCode();
                        });
                        // do not try to merge with above codes, because you can't change the fields which was marked as primary key
                        qualityOrder.QualityOrderDetails.ToList().ForEach(x => {
                            x.UnQualifiedQuantity = x.SuspenseQuantity - x.QualifiedQuantity;
                            ctx.QualityOrderDetails.Attach(x);
                            switch (x.ClassStatus) {
                                case ClassStatus.UnChanged:
                                    ctx.QualityOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Unchanged;
                                    break;
                                case ClassStatus.Updated:
                                    x.ModifiedBy = qualityOrder.ModifiedBy;
                                    x.ModifiedDatetime = DateTime.Now;
                                    ctx.QualityOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Modified;
                                    break;
                                case ClassStatus.Added:
                                    x.CreatedBy = qualityOrder.ModifiedBy;
                                    x.CreatedDatetime = DateTime.Now;
                                    ctx.QualityOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Added;
                                    break;
                                case ClassStatus.Deleted:
                                    ctx.QualityOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Deleted;
                                    break;
                            }
                        });

                        ctx.QualityOrders.Attach(qualityOrder);
                        ctx.Entry(qualityOrder).State = EntityState.Modified;
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public void DeleteMultipleQualityOrder(params int[] qualityOrderIds) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        ctx.QualityOrderDetails.Where(x => qualityOrderIds.Contains(x.QualityOrderId)).ToList().ForEach(x => {
                            ctx.QualityOrderDetails.Remove(x);
                        });
                        ctx.QualityOrders.Where(x => qualityOrderIds.Contains(x.QualityOrderId)).ToList().ForEach(x => {
                            ctx.QualityOrders.Remove(x);
                        });
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public List<QualityOrder> FetchQualityOrderList(QualityOrderSearchModel searchModel, int pageIndex) {
            using (var ctx = this.Context) {
                var query = ctx.QualityOrders
                    .Include("SuspenseOrder")
                    .Include("QualityOrderDetails")
                    .Include("QualityOrderDetails.Material")
                    .Where(x => !string.IsNullOrEmpty(x.Code));

                if (!string.IsNullOrEmpty(searchModel.QualityOrderCode)) {
                    query = query.Where(x => x.Code.Contains(searchModel.QualityOrderCode));
                }
                if (!string.IsNullOrEmpty(searchModel.SuspenseOrderCode)) {
                    query = query.Where(x => x.SuspenseOrder.Code.Contains(searchModel.SuspenseOrderCode));
                }
                if (!string.IsNullOrEmpty(searchModel.MaterialCode)) {
                    query = query.Where(x => x.QualityOrderDetails.Any(y => y.Material.Code.Contains(searchModel.MaterialCode)));
                }
                if (searchModel.QualityDateStart.HasValue) {
                    query = query.Where(x => x.QualityOrderDetails.Any(y => y.CreatedDatetime.Date >= DbFunctions.TruncateTime(searchModel.QualityDateStart.Value)));
                }
                if (searchModel.QualityDateEnd.HasValue) {
                    query = query.Where(x => x.QualityOrderDetails.Any(y => y.CreatedDatetime.Date <= DbFunctions.TruncateTime(searchModel.QualityDateEnd.Value)));
                }

                searchModel.Records = query.Count();
                pageIndex = (pageIndex - 1) * this._pageSize > searchModel.Records ? 1 : pageIndex;

                return query.OrderByDescending(x => x.CreatedDatetime).Skip((pageIndex - 1) * this._pageSize).Take(this._pageSize).ToList();
            }
        }

        public int GetTheMaxFlowNumber(string startString) {
            using (var ctx = this.Context) {
                QualityOrder qualityOrder = ctx.QualityOrders
                    .Where(x => x.Code.StartsWith(startString))
                    .OrderByDescending(x => x.Code)
                    .FirstOrDefault();
                int maxFlowNumber = qualityOrder == null
                    ? 0
                    : Convert.ToInt32(qualityOrder.Code.Substring(qualityOrder.Code.Length - 2, 2));
                return Math.Max(ctx.QualityOrders.Count(x => x.Code.StartsWith(startString)), maxFlowNumber);
            }
        }
    }
}
